package com.wgzx.modbus.entity.response;

import com.wgzx.modbus.constant.FunctionCode;
import com.wgzx.modbus.entity.ModbusRsp;
import io.netty.buffer.ByteBuf;
import lombok.Getter;

/**
 * 请求报文：<br/>
 * 功能码: 1个字节0x04 <br/>
 * 起始地址：2个字节0x0000至0xFFFF <br/>
 * 输入寄存器数量：2个字节0x01至0x007D <br/>
 *
 * 响应报文：<br/>
 * 功能码：1个字节0x04 <br/>
 * 字节数：1个字节 <br/>
 * 输入寄存器 N个字节 <br/>
 *
 * 错误响应：<br/>
 * 差错码：1个字节0x83 <br/>
 * 异常码：1个字节01或02或03或04 <br/>
 *
 * 示例报文：<br/>
 * Rx:00 01(事务ID) 00 00(协议码) 00 06(长度) FF(单元标识符) 04(功能码) 00 00(偏移量) 00 0A(输入寄存器数量，因为2个字节单位，这里10会返回20个字节数据) <br/>
 * Tx:00 01(事务ID) 00 00(协议码) 00 17(长度) FF(单元标识符) 04(功能码) 14(字节数) 00 01 00 00 00 02 00 00 00 03 00 00 00 04 00 00 00 05 00 00(20个字节，正好10组) <br/>
 *
 * @author gexin
 */
@Getter
public class ReadInputRegistersResponse extends ModbusRsp {

    private short byteCount;
    private int[] inputRegisters;

    public ReadInputRegistersResponse(FunctionCode functionCode) {
        super(functionCode);
    }

    @Override
    public void decode(ByteBuf data) {
        byteCount = data.readUnsignedByte();

        inputRegisters = new int[byteCount >> 1];
        for (int i = 0; i < inputRegisters.length; i++) {
            inputRegisters[i] = data.readUnsignedShort();
        }
    }

    @Override
    public String toString() {
        StringBuilder registers = new StringBuilder();
        registers.append("{");
        for (int i = 0; i < inputRegisters.length; i++) {
            registers.append("register_");
            registers.append(i);
            registers.append("=");
            registers.append(inputRegisters[i]);
            registers.append(", ");
        }
        registers.delete(registers.length() - 2, registers.length());
        registers.append("}");

        return "ReadInputRegistersResponse{" + "byteCount=" + byteCount + ", inputRegisters=" + registers + '}';
    }
}
